package com.example.project01.api;

import com.aliyun.oss.OSS;
import com.example.project01.model.Banner;
import com.example.project01.service.BannerService;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.leon.model.I18nException;
import com.leon.model.Pageable;
import com.leon.web.annotation.ApiAuth;
import com.leon.web.annotation.ApiLogger;
import com.leon.web.annotation.ApiSetting;
import com.leon.web.annotation.Condition;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.sql.Timestamp;
import java.util.Objects;


@Slf4j
@Validated
@RestController
@AllArgsConstructor
public class BannerApi {

    private final BannerService bannerService;
    private final OSS oss;

    @GetMapping("/banner")
    @Operation(summary = "获取推荐Banner")
    @ApiSetting(log = @ApiLogger(print = true), auth = @ApiAuth(condition = Condition.PERMITS))
    public ResponseEntity<?> listBanners(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                         @RequestParam(value = "size", defaultValue = "20") Integer size,
                                         @RequestParam(value = "module", defaultValue = "") String module,
                                         @RequestParam(value = "type", defaultValue = "") String type,
                                         @RequestParam(value = "status", defaultValue = "") String status,
                                         @RequestParam(value = "createdAt", required = false)
                                             @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") Timestamp createdAt,
                                         @RequestParam(value = "name", defaultValue = "") String name,
                                         @RequestParam(value = "language", defaultValue = "") String language) {
        return ResponseEntity.ok().body(bannerService.banners(Pageable.of(page, size), module, type, status, createdAt, name, language));
    }

    @Operation(summary = "新增推荐Banner")
    @PostMapping(value = "/banner", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ApiSetting(log = @ApiLogger(print = true), auth = @ApiAuth(condition = Condition.PERMITS))
    public ResponseEntity<?> newBanner(@Valid @RequestBody Banner banner, @RequestPart("file") MultipartFile file) throws I18nException {
        try(var inputStream = new ByteArrayInputStream(file.getBytes())) {
            var ossPathname = "banner/" + banner.getName() + ".jpg";
            this.oss.putObject("banner-image", ossPathname, inputStream);
            String url = file.getOriginalFilename() + "https://t2a-mvno.oss-cn-shanghai.aliyuncs.com/" + ossPathname;
            banner.setImage(url);
        } catch (Exception e) {
            Uploaded uploaded = Uploaded.empty();
            log.error(e.getMessage(), e);
            return ResponseEntity.ok().body(uploaded);
        }
        if (Objects.isNull(banner.getImage())){
            throw new I18nException("banner.image.error");
        }
        int result = bannerService.save(banner, false);
        if (result <= 0){
            throw new I18nException("banner.error");
        }
        return ResponseEntity.ok().build();
    }

    @PutMapping("/banner")
    @Operation(summary = "修改推荐Banner")
    @ApiSetting(log = @ApiLogger(print = true), auth = @ApiAuth(condition = Condition.PERMITS))
    public ResponseEntity<?> updateBanner(@Valid @RequestBody Banner banner) throws I18nException {
        if (Objects.isNull(banner.getId())) {
            throw new I18nException("banner.id.error");
        }
        int result = bannerService.save(banner, true);
        if (result <= 0){
            throw new I18nException("banner.error");
        }
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/banner")
    @Operation(summary = "逻辑删除Banner")
    @ApiSetting(log = @ApiLogger(print = true), auth = @ApiAuth(condition = Condition.PERMITS))
    public ResponseEntity<?> outBanner(@RequestParam Long id) throws I18nException {
        bannerService.deleteBanner(id);
        return ResponseEntity.ok().build();
    }

    public record Uploaded(String name, String path) {
        public static Uploaded empty() {
            return new Uploaded("", "");
        }
    }
}
